package com.leapcloud.crm.server.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.http11.Http11Nio2Protocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.Compression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author motorfu
 * @email ffu@maxleap.com
 * @since 2018/7/2 11:36
 */
@Slf4j
@Configuration
public class TomcatConfig {

  @Value("${server.port}")
  private int port;

  @Value("${server.tomcat.max-threads:1000}")
  private int maxThreads;

  @Value("${server.connection-timeout:5000}")
  private int connectionTimeout;

  @Bean
  public TomcatServletWebServerFactory servletWebServerFactory() {

    log.info("EmbeddedServletContainerFactory port={}, maxThreads={}, connectionTimeout={}", port, maxThreads, connectionTimeout);
    TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
    Compression compression = new Compression();
    compression.setEnabled(true);
    factory.setCompression(compression);
    factory.setProtocol(Http11Nio2Protocol.class.getName());
    factory.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
      Http11Nio2Protocol handler = (Http11Nio2Protocol) connector.getProtocolHandler();
      handler.setPort(port);
      handler.setMaxKeepAliveRequests(-1);
      handler.setAcceptorThreadCount(2);
      handler.setMaxThreads(maxThreads);
      handler.setConnectionTimeout(connectionTimeout);
    });
    return factory;
  }

}
